<template>
  <page-header-wrapper>
    <a-card
      :bordered="false"
      title="详情">
      <div class="table-page-search-wrapper">
        <a-descriptions>
          <a-descriptions-item label="创建时间">
            {{ projectInfo.createTime }}
          </a-descriptions-item>
          <a-descriptions-item label="项目名称">
            {{ projectInfo.projectName }}
          </a-descriptions-item>
          <a-descriptions-item label="项目类型">
            {{ projectInfo.projectTypeName }}
          </a-descriptions-item>
          <a-descriptions-item label="计划交付时间">
            {{ projectInfo.completeTime }}
          </a-descriptions-item>
          <a-descriptions-item label="项目总负责人">
            {{ projectInfo.managerName }}
          </a-descriptions-item>
          <a-descriptions-item label="客户">
            {{ projectInfo.customerName }}
          </a-descriptions-item>
          <a-descriptions-item label="项目状态">
            {{ projectInfo.statusName }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card
      :bordered="false"
      title="合同详情">
      <a-row :gutter="24">
        <a-col :md="12">
          <div class="table-operator">
            <span style="margin-right: 20px">项目合同</span>
            <a-button
              type="primary"
              icon="plus"
              v-if="linkContract"
              @click="contractAdd(true)">关联合同</a-button>
          </div>
          <div>
            <s-table
              ref="projectContractTable"
              size="default"
              rowKey="contractId"
              :columns="contractColumns"
              :data="contractData"
              :showPagination="false">
              <span
                slot="serial"
                slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span
                slot="action"
                slot-scope="text, record">
                <template>
                  <a @click="showContractInfo(record)">详情</a>
                  <a-divider type="vertical" />
                  <a @click="contractRemove(record, true)">移除</a>
                </template>
              </span>
            </s-table>
          </div>
        </a-col>
        <a-col :md="12">
          <div class="table-operator">
            <span style="margin-right: 20px">采购合同</span>
            <a-button
              type="primary"
              icon="plus"
              v-if="linkContract"
              @click="contractAdd(false)">关联合同</a-button>
          </div>
          <div>
            <s-table
              ref="supplierContractTable"
              size="default"
              rowKey="contractId"
              :columns="supplierContractColumns"
              :data="supplierContractData"
              :showPagination="false">
              <span
                slot="serial"
                slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span
                slot="action"
                slot-scope="text, record">
                <template>
                  <a @click="showContractInfo(record)">详情</a>
                  <a-divider type="vertical" />
                  <a @click="contractRemove(record, false)">移除</a>
                </template>
              </span>
            </s-table>
          </div>
        </a-col>
        <contract-form
          ref="contractModal"
          :visible="contractFormVisible"
          :loading="contractFormConfirmLoading"
          @cancel="contractCancel"
          @ok="contractOk" />
      </a-row>
    </a-card>

    <a-card
      :bordered="false"
      title="物品清单详情">
      <!-- 项目所需清单 项目计划采购清单 -->
      <a-row :gutter="24">
        <a-col
          :md="12"
          :style="{paddingRight: '0'}">
          <project-good-list :contractInfo="projectInfo" />
        </a-col>
        <a-col
          :md="12"
          :style="{paddingLeft: '0'}">
          <!-- PorjectPlanBuyList -->
          <project-plan-list
            :addPlanList="addPlanList"
            :contractInfo="projectInfo" />
        </a-col>
      </a-row>
      <!-- 采购清单 实际交付清单 -->
      <a-spin :spinning="goodLoading">
        <a-row :gutter="24">
          <a-col
            :md="12"
            :style="{paddingRight: '0'}">
            <buy-list
              ref="buyListRef"
              :listsubmit="listsubmit"
              :contractInfo="projectInfo"
              :buyLists="buyLists"
              :dealBuyLists="dealBuyLists"
              :loading="listLoading"
              :money="buyListsMoney"
              @submitAll="submitAll"
              @ok="() => submitGoods()" />
          </a-col>
          <a-col
            :md="12"
            :style="{paddingLeft: '0'}">
            <deal-buy-list
              ref="dealbuyListRef"
              :listRollBack="listRollBack"
              :contractInfo="projectInfo"
              :dealBuyLists="dealBuyLists"
              :money="dealMoney"
              @ok="() => abortGoods()"
              :loading="listLoading" />
          </a-col>
        </a-row>
      </a-spin>
    </a-card>
    <project-progress
      ref="taskProgress"
      v-if="showProjectProgress"
      :project="projectInfo" />
    <a-card
      :bordered="false"
      title="团队成员">
      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="teamSave"
          @click="memberAdd">新增</a-button>
      </div>
      <div>
        <s-table
          ref="teamTable"
          size="default"
          rowKey="teamId"
          :columns="teamColumns"
          :data="teamData"
          :showPagination="false">
          <span
            slot="serial"
            slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span
            slot="sex"
            slot-scope="text, record">
            {{ record.sex===0?'男':'女' }}
          </span>
          <span
            slot="action"
            slot-scope="text, record">
            <template>
              <a
                v-if="teamUpdate"
                @click="memberEdit(record)">编辑</a>
              <a-divider
                type="vertical" />
              <a
                v-if="teamDelete"
                @click="memberDel(record)">移除</a>
            </template>
          </span>
        </s-table>
      </div>
      <member-form
        ref="memberModal"
        :visible="memberFormVisible"
        :loading="memberFormConfirmLoading"
        @cancel="memberCancel"
        @ok="memberOk" />
    </a-card>
    <a-card
      :bordered="false"
      title="任务管理">
      <div class="table-operator">
        <a-row :gutter="24">
          <a-col :md="8">
            <a-button
              type="primary"
              icon="plus"
              v-if="task1save"
              @click="() => taskAdd(1,{})">新建一级任务</a-button>
            <a-button
              type="primary"
              icon="plus"
              v-if="task"
              @click="taskFileAdd">添加附件</a-button>
          </a-col>
        </a-row>
      </div>
      <div>
        <a-row :gutter="24">
          <a-col :md="16">
            <s-table
              ref="taskTable"
              size="default"
              rowKey="taskId"
              :columns="taskColumns"
              :data="taskData"
              :showPagination="false"
              :customRow="taskCustomRow">
              <span
                slot="status"
                slot-scope="text, record">
                <template>
                  {{ record.statusName? record.statusName : record.progressName }}
                </template>
              </span>
              <span
                slot="action"
                slot-scope="text, record">
                <template>
                  <a
                    v-show="(record && record.taskLevel !==3)"
                    v-if="(record && record.taskLevel === 1 && task2save) || (record.taskLevel === 2 && task3save) "
                    @click="taskAdd(record.taskLevel + 1, record)">新建子任务</a>
                  <a-divider
                    v-if="(record && record.taskLevel === 1 && task2save) || (record.taskLevel === 2 && task3save) "
                    v-show="record && record.taskLevel !==3"
                    type="vertical" />
                  <a
                    v-if="showFinish(record) && ((record && record.taskLevel === 1 && task1update) || (record.taskLevel === 2 && task2update) || (record.taskLevel === 3 && task3update))"
                    @click="taskEdit(record, record.taskLevel)">编辑</a>
                  <a-divider
                    v-if="showFinish(record) && ((record && record.taskLevel === 1 && task1update) || (record.taskLevel === 2 && task2update) || (record.taskLevel === 3 && task3update))"
                    type="vertical" />
                  <!-- 展示完成按钮1.只有2 3 级任务有。2.未完成的任务 -->
                  <a
                    v-if="showFinish(record) && (record && record.taskLevel === 2 && task2complete) || (record.taskLevel === 3 && task3complete) "
                    @click="taskFinish(record)">完成</a>
                  <a-divider
                    v-show="record && record.taskLevel === 3 || !record.children"
                    type="vertical" />
                  <a
                    v-if="(record.taskLevel === 3 || !record.children) && ((record && record.taskLevel === 1 && task1delete) || (record.taskLevel === 2 && task2delete) || (record.taskLevel === 3 && task3delete))"
                    @click="deleteTask(record)">删除</a>
                </template>
              </span>
            </s-table>
          </a-col>
          <a-col :md="8">
            <a-table
              ref="fileTable"
              size="default"
              rowKey="fildId"
              :columns="fileColumns"
              :dataSource="taskFiles"
              :pagination="false">
              <span
                slot="serial"
                slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span
                slot="fileName"
                slot-scope="text, record">
                <a
                  target="blank"
                  :href="record.fileUrl"
                  :download="record.fileName">{{ record.fileName }}</a>
              </span>
              <span
                slot="action"
                slot-scope="text, record">
                <template>
                  <a
                    @click="handleShowImg(record)">预览</a>
                  <a-divider type="vertical" />
                  <a @click="taskFileDelete(record)">删除</a>
                </template>
              </span>
            </a-table>
            <file-create-form
              ref="taskFileCreateForm"
              :visible="taskFileCreateVisible"
              :loading="taskFileLoading"
              @cancel="taskFileCancel"
              @ok="taskFileOk" />
          </a-col>
        </a-row>
        <a-row
          :gutter="24"
          v-if="(task && task['taskLevel'] === 1 && task1info) || (task && task['taskLevel'] === 2 && task2info) || (task && task['taskLevel'] === 3 && task3info)"
        >
          <a-col :md="24">
            <a-descriptions
              title="任务详情"
              :column="2">
              <a-descriptions-item label="任务名称">
                {{ task.taskName }}
              </a-descriptions-item>
              <a-descriptions-item label="任务目标">
                {{ task.taskTarget }}
              </a-descriptions-item>
              <a-descriptions-item label="指标">
                {{ task.taskKpi }}
              </a-descriptions-item>
              <a-descriptions-item label="开始日期">
                {{ task.beginDate }}
              </a-descriptions-item>
              <a-descriptions-item label="计划交付日期">
                {{ task.planCompleteDate }}
              </a-descriptions-item>
              <a-descriptions-item label="实际完成日期">
                {{ task.completeDate }}
              </a-descriptions-item>
              <a-descriptions-item label="执行人员">
                {{ task.userNames }}
              </a-descriptions-item>
              <a-descriptions-item label="任务类型">
                {{ task.taskTypeName }}
              </a-descriptions-item>
              <a-descriptions-item
                label="状态"
                v-if="task && task['taskLevel'] === 3">
                {{ task.statusName }}
              </a-descriptions-item>
              <a-descriptions-item
                label="状态"
                v-if="task && task['taskLevel'] === 2">
                {{ task.progressName }}
              </a-descriptions-item>
              <a-descriptions-item label="完成质量">
                {{ task.completeQualityName }}
              </a-descriptions-item>
              <a-descriptions-item label="备注">
                {{ task.note }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
        </a-row>
      </div>
      <task-form
        ref="taskModal"
        :users="teamUsers"
        :taskLevel1="taskLevel1"
        :taskLevel2="taskLevel2"
        :taskLevel3="taskLevel3"
        :visible="taskFormVisible"
        :loading="taskFormConfirmLoading"
        @cancel="taskCancel"
        @ok="taskOk" />
      <a-modal
        title="图片预览"
        width="800"
        :visible="showImg"
        :footer="null"
        @cancel="() => {this.showImg = false}">
        <div style="display: flex;justify-content: center">
          <img style="width: 700px" :src="imgUrl" />
        </div>
      </a-modal>
    </a-card>
    <Performance v-if="showPerform" :projectInfoProps="projectInfo" :teamUsers="teamUsers" />
  </page-header-wrapper>
</template>

<script>
import Performance from './modules/performance/Performance'
import { STable, Ellipsis, Bar } from '@/components'
import { getTeamByProject, saveTeamByProject, updateTeamByProject, deleteTeamByProject } from '@/api/team'
import {
  delFileById,
  getGoodsSelect,
  getFileByIds,
  getTaskList,
  selectContractList,
  updateContract,
  updateTask,
  saveTask,
  deleteTask,
  progressTask,
  statusTask,
  batchDelivery
} from '@/api/manage'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'
import {
  filterEmptyPro,
  productColumns,
  productColumns2,
  teamColumns,
  taskColumns,
  fileColumns,
  contractColumns,
  supplierContractColumns,
  showFinish
} from './config'
import CreateForm from './modules/CreateForm'
import MemberForm from '@/views/project/modules/MemberForm'
import ProductForm from '@/views/project/modules/ProductForm'
import TaskForm from '@/views/project/modules/TaskForm'
import ContractForm from '@/views/project/modules/ContractForm'
import FileCreateForm from '@/views/project/modules/FileCreateForm'
import ProjectProgress from './block/ProjectProgress'
import BuyList from './block/BuyList'
import DealBuyList from './block/DealBuyList'
import ProjectPlanList from './block/ProjectPlanList'
import ProjectGoodList from './block/ProjectGoodList'
import { message } from 'ant-design-vue'
export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    MemberForm,
    ProductForm,
    Performance,
    TaskForm,
    Bar,
    ContractForm,
    FileCreateForm,
    ProjectProgress,
    BuyList,
    DealBuyList,
    ProjectPlanList,
    ProjectGoodList
  },
  data () {
    this.productColumns = productColumns
    this.teamColumns = teamColumns
    this.taskColumns = taskColumns
    this.fileColumns = fileColumns
    this.contractColumns = contractColumns
    this.supplierContractColumns = supplierContractColumns
    this.productColumns2 = productColumns2
    return {
      // 预览
      showImg: false,
      imgUrl: '',
      // 权限
      linkContract: true, // 关联合同
      teamSave: true, // add
      teamList: true, // search
      teamDelete: true, // delete
      teamUpdate: true, // update
      showProjectProgress: true, // 展示项目进度
      addPlanList: true, // 新增计划采购清单
      listsubmit: true, // 清单交付
      listRollBack: true, // 清单撤销交付
      // 1级任务增删改查
      task1save: true,
      task1update: true,
      task1delete: true,
      task1info: true,
      // 2级任务增删改完成
      task2save: true,
      task2update: true,
      task2delete: true,
      task2info: true,
      task2complete: true,
      // 3级任务增删改完成
      task3save: true,
      task3update: true,
      task3delete: true,
      task3info: true,
      task3complete: true,
      // create model
      visible: false,
      confirmLoading: false,
      // 合同
      contractFormVisible: false,
      contractFormConfirmLoading: false,
      contractIsEdit: false,
      isProjectContract: false,
      // 团队
      memberFormVisible: false,
      teamUsers: [],
      memberFormConfirmLoading: false,
      memberIsEdit: false,
      memberFormMdl: null,
      // 实际采购清单 实际交付清单
      goodLoading: false,
      buyLists: undefined,
      buyListsMoney: 0,
      dealBuyLists: undefined,
      dealMoney: 0,
      listLoading: false,
      allSubmitList: [],
      // 任务管理
      // users: [],
      taskLevel1: false,
      taskLevel2: false,
      taskLevel3: false,
      isTaskAdd: false,
      isTaskEdit: false,
      currentTask: undefined,
      taskFormVisible: false,
      taskFormConfirmLoading: false,
      taskFileCreateVisible: false,
      taskFileLoading: false,
      task: undefined,
      taskFiles: [],
      clicktaskID: null,
      // 对应绩效展示
      showPerform: false,
      // 查询参数
      queryParam: {},
      showFinish: e => showFinish(e),
      // 加载数据方法 必须为 Promise 对象
      contractData: parameter => {
        return selectContractList({
          projectId: this.projectInfo.projectId,
          // 项目合同
          contractType: 1
        }).then(res => {
          return res
        })
      },
      supplierContractData: parameter => {
        return selectContractList({
          projectId: this.projectInfo.projectId,
          // 项目合同
          contractType: 2
        }).then(res => {
          return res
        })
      },
      teamData: parameter => {
        return getTeamByProject({ projectId: this.projectInfo.projectId }).then(res => {
          const _userId = localStorage.getItem('userId')
          this.teamUsers = res.data
          if (res.data.map(item => item.userId).indexOf(_userId) !== -1) {
             this.initPermission()
          }
          return res
        })
      },
      taskData: parameter => {
        const requestParameters = { page: 1, limit: 9999, projectId: this.projectInfo.projectId }
        return getTaskList(Object.assign({}, this.queryParam, requestParameters)).then(res => {
          return Object.assign({}, res, {
            totalCount: res.total,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          })
        })
      },
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      projectInfo: {}
    }
  },
  created () {
    if (!isInMenu(this.menu, 'rec:project')) {
      this.initPermission()
    }
    this.init()
  },
  mounted () {
    this.getGoods()
    // allStaff().then(res => {
    //   this.users = res.data
    // })
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    initPermission () {
    this.linkContract =
      isInMenu(this.menu, 'ROLE_but:contract:select') &&
      isInMenu(this.menu, 'ROLE_but:contract:info') &&
      isInMenu(this.menu, 'ROLE_but:contract:update') &&
      isInMenu(this.menu, 'ROLE_but:project:linkContract')
    this.teamSave = isInMenu(this.menu, 'ROLE_but:team:save') && isInMenu(this.menu, 'ROLE_but:user:select')
    this.teamList = isInMenu(this.menu, 'ROLE_but:team:project')
    this.teamDelete = isInMenu(this.menu, 'ROLE_but:team:delete')
    this.showProjectProgress = isInMenu(this.menu, 'ROLE_but:project:speed')
    this.teamUpdate = isInMenu(this.menu, 'ROLE_but:team:update') && isInMenu(this.menu, 'ROLE_but:user:select')
    this.addPlanList = isInMenu(this.menu, 'ROLE_but:supplier:select') && isInMenu(this.menu, 'ROLE_but:goods:save')
    this.listsubmit = isInMenu(this.menu, 'ROLE_but:goods:update')
    this.listRollBack = isInMenu(this.menu, 'ROLE_but:goods:update')

    this.task1save = isInMenu(this.menu, 'ROLE_but:firstTask:save') && isInMenu(this.menu, 'ROLE_but:user:select')
    this.task1update = isInMenu(this.menu, 'ROLE_but:firstTask:update')
    this.task1delete = isInMenu(this.menu, 'ROLE_but:firstTask:delete')
    this.task1info = isInMenu(this.menu, 'ROLE_but:firstTask:info')

    this.task2save = isInMenu(this.menu, 'ROLE_but:secondTask:save') && isInMenu(this.menu, 'ROLE_but:user:select')
    this.task2update = isInMenu(this.menu, 'ROLE_but:secondTask:update')
    this.task2delete = isInMenu(this.menu, 'ROLE_but:secondTask:delete')
    this.task2info = isInMenu(this.menu, 'ROLE_but:secondTask:info')
    this.task2complete = isInMenu(this.menu, 'ROLE_but:task:progress')

    this.task3save = isInMenu(this.menu, 'ROLE_but:thirdTask:save') && isInMenu(this.menu, 'ROLE_but:user:select')
    this.task3update = isInMenu(this.menu, 'ROLE_but:thirdTask:update')
    this.task3delete = isInMenu(this.menu, 'ROLE_but:thirdTask:delete')
    this.task3info = isInMenu(this.menu, 'ROLE_but:thirdTask:info')
    this.task3complete = isInMenu(this.menu, 'ROLE_but:task:status')
    // 绩效操作权限
    this.showPerform = isInMenu(this.menu, 'ROLE_but:incentive:search')
    },
    submitAll () {
      // const goodsList = this.buyLists.map(item => ({ goodsId: item.goodsId, count: item.count }))
      // console.log(goodsList)
      this.goodLoading = true
      batchDelivery(JSON.stringify(this.allSubmitList)).finally(() => { this.getGoods(); this.goodLoading = false })
    },
    init () {
      this.projectInfo = JSON.parse(this.$route.query.record)
    },
    getGoods () {
      this.listLoading = true
      // 34 项目详情获取 采购和交付清单
      getGoodsSelect({ type: 34, projectId: this.projectInfo.projectId })
        .then(res => {
          const _buyList = []
          const _dealbuyList = []
          const _allSubmitList = []
          res.data.map(item => {
            const buyItem = item['3']
            const dealItem = item['4']
            const _buyItem = Object.assign(buyItem, { leftCount: buyItem.count - dealItem.count })
            _buyList.push(_buyItem)
            _dealbuyList.push(dealItem || {})
            _allSubmitList.push(Object.assign({}, dealItem, { count: buyItem.count }))
          })
          this.allSubmitList = _allSubmitList
          this.buyLists = _buyList
          this.dealBuyLists = _dealbuyList
        })
        .finally(() => {
          let total = 0
          this.dealBuyLists.map(item => {
            total += item.count * item.price
          })
          this.dealMoney = total

          total = 0
          this.buyLists.map(item => {
            total += item.count * item.price
          })
          this.buyListsMoney = total
          this.listLoading = false
        })
    },
    // 交付
    submitGoods (record) {
      // 交付清单 重新刷新一遍数据
      this.$refs.buyListRef.handleDeal(record).finally(() => {
        this.getGoods()
      })
    },
    // 撤销交付
    abortGoods (record) {
      // 交付清单 重新刷新一遍数据
      this.$refs.dealbuyListRef.handleDeal(record).finally(() => {
        this.getGoods()
      })
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleOk () {
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleInfo () {},
    next () {
      this.current++
    },
    prev () {
      this.current--
    },
    // 项目合同
    contractAdd (isProjectContract) {
      // 重置表单
      this.$refs.contractModal.form.resetFields()
      this.isProjectContract = isProjectContract
      // 初始化
      this.$refs.contractModal.init()
      // 展示新增表单
      this.contractFormVisible = true
      // 合同类型
      this.$refs.contractModal.selectContractList2(isProjectContract)
    },
    contractEdit (record) {
      // 重置表单
      this.$refs.memberModal.form.setFieldsValue(record)
      // 展示新增表单
      this.memberFormVisible = true
      // 表单状态
      this.memberIsEdit = true
    },
    contractRemove (record, isProjectContract) {
      this.isProjectContract = isProjectContract
      record.projectId = 0
      const pam = filterEmptyPro(record)
      updateContract(Object.assign({}, pam, { projectId: 0 })).then(res => {
        if (res.code === 0) {
          // 刷新表格
          if (this.isProjectContract) {
            // 刷新项目合同表格
            this.$refs.projectContractTable.refresh()
          } else {
            // 刷新采购合同表格
            this.$refs.supplierContractTable.refresh()
          }
          this.$message.success('移除成功')
        }
      })
    },
    contractOk () {
      const form = this.$refs.contractModal.form
      this.contractFormConfirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const _contract = this.$refs.contractModal.contract
          const pam = filterEmptyPro(_contract)
          // 关联合同
          updateContract(Object.assign({}, pam, { projectId: this.projectInfo.projectId }))
            .then(res => {
              if (res.code === 0) {
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                if (this.isProjectContract) {
                  // 刷新项目合同表格
                  this.$refs.projectContractTable.refresh()
                } else {
                  // 刷新采购合同表格
                  this.$refs.supplierContractTable.refresh()
                }
                // 展示新增表单
                this.contractFormVisible = false
                this.$message.success('关联成功')
              }
            })
            .finally(res => {
              this.contractFormConfirmLoading = false
            })
        } else {
          this.contractFormConfirmLoading = false
        }
      })
    },
    contractCancel () {
      this.contractFormVisible = false
      const form = this.$refs.contractModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    showContractInfo (record) {
      this.$router.push({
        name: 'contractInfo',
        path: '/contract/contractInfo',
        query: {
          contractId: record.contractId
        }
      })
    },
    // 团队成员
    memberAdd () {
      // 重置表单
      this.$refs.memberModal.form.resetFields()
      // 展示新增表单
      this.memberFormVisible = true
      // 表单状态
      this.memberIsEdit = false
    },
    memberEdit (record) {
      // 重置表单
      this.$refs.memberModal.form.setFieldsValue(record)
      // 展示新增表单
      this.memberFormVisible = true
      // 表单状态
      this.memberIsEdit = true
    },
    memberDel (record) {
      deleteTeamByProject(Object.assign({}, record)).then(res => {
        if (res.code === 0) {
          // 刷新表格
          this.$refs.teamTable.refresh()
          this.$message.info('删除成功')
        }
      })
    },
    memberOk () {
      const form = this.$refs.memberModal.form
      this.memberFormConfirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.memberIsEdit) {
            // 修改
            updateTeamByProject(Object.assign({}, values, { projectId: this.projectInfo.projectId }))
              .then(res => {
                if (res.code === 0) {
                  this.memberFormVisible = false
                  // 重置表单数据
                  form.resetFields()
                  // 刷新表格
                  this.$refs.teamTable.refresh()
                  this.$message.info('修改成功')
                }
              })
              .finally(res => {
                this.memberFormConfirmLoading = false
              })
          } else {
            // 新增
            saveTeamByProject(Object.assign({}, values, { projectId: this.projectInfo.projectId }))
              .then(res => {
                if (res.code === 0) {
                  this.memberFormVisible = false
                  // 重置表单数据
                  form.resetFields()
                  // 刷新表格
                  this.$refs.teamTable.refresh()
                  this.$message.info('新增成功')
                }
              })
              .finally(res => {
                this.memberFormConfirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    memberCancel () {
      this.memberFormVisible = false
      const form = this.$refs.memberModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 采购清单
    productAdd () {
      this.productFormMdl = null
      this.productFormVisible = true
    },
    productEdit (record) {
      this.productFormVisible = true
      this.productFormMdl = { ...record }
    },
    productOk () {
      const form = this.$refs.productModal.form
      this.productFormConfirmLoading = true
      form.validateFields((errors, values) => {})
    },
    productCancel () {
      this.productFormVisible = false

      const form = this.$refs.productModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 任务管理
    taskAdd (taskLevel, record) {
      this.currentTask = record
      switch (taskLevel) {
        case 1:
          this.taskLevel1 = true
          this.taskLevel2 = false
          this.taskLevel3 = false
          break
        case 2:
          this.taskLevel1 = false
          this.taskLevel2 = true
          this.taskLevel3 = false
          break
        case 3:
          this.taskLevel1 = false
          this.taskLevel2 = false
          this.taskLevel3 = true
          break
        default:
          this.taskLevel1 = false
          this.taskLevel2 = false
          this.taskLevel3 = false
          break
      }
      this.taskFormMdl = null
      this.taskFormVisible = true
      this.isTaskAdd = true
      this.isTaskEdit = false
      this.$nextTick(() => {
        this.$refs.taskModal.form.setFieldsValue({ taskType: 1 })
      })
    },
    taskFinish (record) {
      if (record.taskLevel === 2) {
        progressTask({ taskId: record.taskId, taskLevel: 2, progress: 3 }).then(res => {
          message.success('任务完成')
          this.$refs.taskTable.refresh()
          this.$refs.taskProgress.getTask()
        })
      } else if (record.taskLevel === 3) {
        statusTask({ taskId: record.taskId, taskLevel: 3, status: 3 }).then(res => {
          message.success('任务完成')
          this.$refs.taskTable.refresh()
          this.$refs.taskProgress.getTask()
        })
      }
    },
    deleteTask (record) {
      deleteTask()
    },
    taskEdit (record, taskLevel) {
      this.currentTask = record
      switch (taskLevel) {
        case 1:
          this.taskLevel1 = true
          this.taskLevel2 = false
          this.taskLevel3 = false
          break
        case 2:
          this.taskLevel1 = false
          this.taskLevel2 = true
          this.taskLevel3 = false
          break
        case 3:
          this.taskLevel1 = false
          this.taskLevel2 = false
          this.taskLevel3 = true
          break
        default:
          this.taskLevel1 = false
          this.taskLevel2 = false
          this.taskLevel3 = false
          break
      }
      this.taskFormVisible = true
      this.isTaskAdd = false
      this.isTaskEdit = true
      this.$nextTick(() => {
        this.$refs.taskModal.form.setFieldsValue(
          Object.assign(record, { taskType: 1, userIds: record?.userIds?.split(',').map(item => Number(item)) || [] })
        )
      })
    },
    taskOk () {
      const form = this.$refs.taskModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.isTaskAdd) {
            this.taskFormConfirmLoading = true
            const param = Object.assign({}, values, {
              projectId: this.projectInfo.projectId,
              parentId: this.currentTask?.taskId,
              userIds: values.userIds?.length ? values.userIds.join(',') : String(values.userIds),
              taskLevel: this.currentTask?.taskLevel ? this.currentTask.taskLevel + 1 : 1
            })
            saveTask(param)
              .then(res => {
                message.success('新增任务成功')
                this.taskFormVisible = false
                form.resetFields()
                this.$refs.taskProgress.getTask()
              })
              .finally(res => {
                this.taskFormConfirmLoading = false
                this.$refs.taskTable.refresh()
              })
          } else if (this.isTaskEdit) {
            this.taskFormConfirmLoading = true
            const param = Object.assign({}, values, {
              projectId: this.projectInfo.projectId,
              parentId: this.currentTask?.parentId,
              userIds: values.userIds?.length ? values.userIds.join(',') : String(values.userIds),
              taskId: this.currentTask.taskId,
              fileIds: this.currentTask.fileIds,
              taskLevel: this.currentTask.taskLevel
            })
            updateTask(param)
              .then(res => {
                message.success('编辑任务成功')
                this.taskFormVisible = false
                form.resetFields()
                this.$refs.taskProgress.getTask()
              })
              .finally(res => {
                this.taskFormConfirmLoading = false
                this.$refs.taskTable.refresh()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    taskCancel () {
      this.taskFormVisible = false
      const form = this.$refs.taskModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    taskCustomRow (record, index) {
      return {
        style: {
          'background-color': record.taskId === this.clicktaskID ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.clicktaskID = record.taskId
            this.task = record
            this.taskGetFiles(record)
          }
        }
      }
    },
    taskGetFiles (record) {
      if (record.fileIds) {
        getFileByIds({ fileIds: record.fileIds }).then(res => {
          this.taskFiles = res.data
        })
      } else {
        this.taskFiles = []
      }
    },
    taskFileAdd () {
      const arr = Object.keys(this.task)
      if (arr.length === 0) {
        this.$message.error('请先选择任务')
      } else {
        this.$refs.taskFileCreateForm.resetFileList()
        this.taskFileCreateVisible = true
      }
    },
    taskFileCancel () {
      this.$refs.taskFileCreateForm.resetFileList()
      this.taskFileCreateVisible = false
    },
    taskFileOk () {
      const form = this.$refs.taskFileCreateForm.form
      form.validateFields((errors, values) => {
        if (!errors) {
          const task = this.task
          if (task.fileIds) {
            task.fileIds = task.fileIds + ',' + values.fileIds
          } else {
            task.fileIds = values.fileIds
          }
          updateTask(
            Object.assign({}, task, {
              fileIds: task.fileIds,
              children: []
            })
          ).then(res => {
            if (res.code === 0) {
              this.taskFileCreateVisible = false
              form.resetFields()
              this.taskGetFiles(task)
              this.$message.info('新增成功')
            }
          })
        }
      })
    },
    taskFileDelete (record) {
      const fileIds = this.task.fileIds.split(',')
      const newFileIds = []
      for (const id of fileIds) {
        if (id !== record.fileId.toString()) {
          newFileIds.push(id)
        }
      }
      this.task.fileIds = newFileIds.join(',')
      delFileById(
        Object.assign(
          {},
          {
            fileId: record.fileId
          }
        )
      ).then(res1 => {
        if (res1.code === 0) {
          updateTask(
            Object.assign({}, this.task, {
              fileIds: this.task.fileIds,
              children: []
            })
          ).then(res => {
            if (res.code === 0) {
              this.taskGetFiles(this.task)
              this.$message.info('删除成功')
            }
          })
        }
      })
    },
    handleShowImg (record) {
      this.showImg = true
      this.imgUrl = record?.fileUrl
    }
  }
}
</script>
<style scoped>
.steps-content {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 80px;
}

.steps-action {
  margin-top: 24px;
}
</style>

<style lang="less" scoped>
.extra-wrapper {
  line-height: 55px;
  padding-right: 24px;

  .extra-item {
    display: inline-block;
    margin-right: 24px;

    a {
      margin-left: 24px;
    }
  }
}
/deep/.ant-table-wrapper{
  max-height: 800px;
  overflow: scroll;
}

.antd-pro-pages-dashboard-analysis-twoColLayout {
  position: relative;
  display: flex;
  display: block;
  flex-flow: row wrap;
}

.antd-pro-pages-dashboard-analysis-salesCard {
  height: calc(100% - 24px);
  /deep/ .ant-card-head {
    position: relative;
  }
}

.dashboard-analysis-iconGroup {
  i {
    margin-left: 16px;
    color: rgba(0, 0, 0, 0.45);
    cursor: pointer;
    transition: color 0.32s;
    color: black;
  }
}
.analysis-salesTypeRadio {
  position: absolute;
  right: 54px;
  bottom: 12px;
}
</style>
